<template>
  <div class="gpt-root">
    <!-- 初始问答模式 -->
    <div v-if="mode === 'chat'" class="gpt-chat-init">
      <div class="gpt-chat-center">
        <div class="gpt-logo">
          <!-- <img src="../../assets/logo/" alt="logo" /> -->
        </div>
        <div class="gpt-title">智能问答</div>
        <div class="gpt-desc">请输入您的问题，系统将结合本地知识库和AI为您解答</div>
        <div class="gpt-input-row">
          <el-input
            v-model="question"
            type="textarea"
            :rows="1"
            resize="none"
            class="gpt-input"
            placeholder="请输入您的问题..."
            @keyup.enter="handleAsk"
          />
          <el-button type="primary" class="gpt-send-btn" @click="handleAsk">
            <el-icon><Promotion /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
    <!-- 提问后主界面 -->
    <div v-else class="gpt-main">
      <!-- 左侧 -->
      <div class="gpt-left">
        <!-- 聊天对话流（历史问答） -->
        <div class="gpt-history">
          <div v-if="chatList.length === 0" class="gpt-welcome">
            <div class="welcome-icon">💬</div>
            <div class="welcome-title">开始新的对话</div>
            <div class="welcome-desc">输入您的问题，AI将结合知识库为您解答</div>
          </div>
          <template v-else v-for="(msg, idx) in chatList" :key="idx">
            <div :class="['gpt-message', msg.role]">
              <div class="message-avatar">
                <div :class="['avatar', msg.role]">
                  <el-icon v-if="msg.role === 'user'"><User /></el-icon>
                  <el-icon v-else>AI</el-icon>
                </div>
              </div>
              <div :class="['gpt-bubble', msg.role]">
                <!-- 如果是加载状态，显示动画 -->
                <div v-if="msg.content === 'loading'" class="loading-animation">
                  <div class="loading-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                  <div class="loading-text">正在思考中...</div>
                </div>
                <!-- 否则显示正常内容 -->
                <template v-else>
                  {{ msg.content }}
                </template>
              </div>
            </div>
            <!-- 仅AI消息展示目录结构，紧跟在气泡下方 -->
            <template v-if="msg.role === 'ai' && msg.dirs && msg.dirs.length > 0">
              <div class="gpt-dir-list-compact">
                <div class="gpt-dir-header">
                  <span class="gpt-dir-title">📚 知识库路径</span>
                  <span class="gpt-dir-subtitle">选择相关路径进行后续操作</span>
                </div>
                <div class="gpt-dir-items">
                  <div
                    v-for="dir in msg.dirs"
                    :key="dir.id"
                    class="gpt-dir-item"
                    :class="{ selected: selectedDirIds.includes(dir.id) }"
                    @click="toggleDir(dir.id)"
                  >
                    <div class="gpt-dir-checkbox">
                      <el-checkbox 
                        :model-value="selectedDirIds.includes(dir.id)" 
                        @change.stop="toggleDir(dir.id)"
                        size="large"
                      />
                    </div>
                    <div class="gpt-dir-content">
                      <div class="gpt-dir-path">
                        <template v-for="(node, idx) in dir.path" :key="node.id">
                          <span class="gpt-dir-path-label">{{ node.label }}</span>
                          <span v-if="idx < dir.path.length - 1" class="gpt-dir-path-sep">/</span>
                        </template>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 目录结构下方显示按钮 -->
                <div class="gpt-dir-actions">
                  <el-button 
                    size="small" 
                    type="primary"
                    :disabled="!selectedDirIds.length" 
                    @click="handlePolish"
                    class="action-btn"
                  >
                    <el-icon><EditPen /></el-icon>
                    润色
                  </el-button>
                  <el-button 
                    size="small" 
                    type="success"
                    :disabled="!selectedDirIds.length" 
                    @click="handleOriginalQA"
                    class="action-btn"
                  >
                    <el-icon><QuestionFilled /></el-icon>
                    原文问答
                  </el-button>
                  <el-button 
                    size="small" 
                    type="warning"
                    :disabled="!selectedDirIds.length" 
                    @click="handleKnowledgeQA"
                    class="action-btn"
                  >
                    <el-icon><Search /></el-icon>
                    对知识库提问
                  </el-button>
                </div>
              </div>
            </template>
          </template>
        </div>
        <!-- 左侧底部固定提问框 -->
        <div class="gpt-input-area-fixed">
          <div class="gpt-input-status">
            <span class="status-indicator">
              <span class="status-dot"></span>
              {{ chatList.length > 0 ? '对话中' : '就绪' }}
            </span>
            <div class="status-actions">
              <el-button 
                v-if="chatList.length > 0"
                size="small" 
                type="info" 
                @click="clearChatHistory"
                class="reset-btn"
                title="重置会话"
              >
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <span class="help-text">
                <el-tooltip content="按 Enter 键快速发送，Shift + Enter 换行" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </span>
            </div>
          </div>
          <div class="gpt-input-row">
            <el-input
              v-model="question"
              type="textarea"
              :rows="1"
              resize="none"
              class="gpt-input"
              placeholder="请输入您的问题..."
              @keydown.enter="handleKeyDown"
              aria-label="问题输入框"
              role="textbox"
            />
            <el-button 
              type="primary" 
              class="gpt-send-btn" 
              @click="handleAsk"
              :loading="knowledgeLoading"
              :disabled="knowledgeLoading"
              aria-label="发送问题"
              :title="knowledgeLoading ? '正在处理...' : '发送问题'"
            >
              <el-icon v-if="!knowledgeLoading"><Promotion /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="gpt-right">
                  <div class="gpt-content-scroll">
            <div v-if="knowledgeError" class="gpt-error">
              <div class="error-icon">⚠️</div>
              <div class="error-title">加载失败</div>
              <div class="error-desc">{{ knowledgeError }}</div>
              <el-button size="small" @click="loadKnowledgeTree" class="retry-btn">
                <el-icon><Refresh /></el-icon>
                重试
              </el-button>
            </div>
            <div v-else-if="!selectedDirIds.length" class="gpt-tip">
              <div class="tip-icon">📚</div>
              <div class="tip-title">选择知识目录</div>
              <div class="tip-desc">请从左侧选择知识目录，查看相关片段内容</div>
            </div>
            <div v-else-if="knowledgeLoading" class="gpt-skeleton">
              <div class="skeleton-item"></div>
              <div class="skeleton-item"></div>
              <div class="skeleton-item"></div>
              <div class="skeleton-item"></div>
              <div class="skeleton-item"></div>
            </div>
            <div v-else>
            <div v-for="frag in currentFragments" :key="frag.id" class="gpt-fragment-card">
              <!-- 展示态 -->
              <div v-if="editId !== frag.id">
                <div class="gpt-fragment-toolbar">
                  <el-button size="small" type="primary" @click="startEdit(frag)">
                    <el-icon><EditPen /></el-icon>
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click="handleDelete(frag)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
                <div class="gpt-fragment-rich" v-html="frag.content"></div>
                <div class="gpt-fragment-meta">
                  <span class="meta-item">
                    <el-icon><Clock /></el-icon>
                    知识片段
                  </span>
                </div>
              </div>
              <!-- 编辑态 -->
              <div v-else>
                <div class="gpt-fragment-toolbar edit-mode">
                  <el-button size="small" type="primary" @click="saveEdit(frag)">
                    <el-icon><Check /></el-icon>
                    保存
                  </el-button>
                  <el-button size="small" @click="cancelEdit">
                    <el-icon><Close /></el-icon>
                    取消
                  </el-button>
                </div>
                <div
                  class="gpt-fragment-editable"
                  contenteditable="true"
                  ref="editDivRef"
                  @input="onEditInput"
                  @paste="handlePaste"
                  v-html="editContent"
                ></div>
                <div style="color: #888; font-size: 12px; margin-top: 4px"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { Promotion, Clock, EditPen, Delete, Check, Close, QuestionFilled, Refresh, User } from '@element-plus/icons-vue';
import { dirTree, fragments } from '@/api/knowledge';
import { searchKnowledge } from '@/api/chat';

const mode = ref('chat');
const question = ref('');
const chatList = ref([]);
const selectedDirIds = ref([]);
const currentFragmentsMap = ref({});

// 知识库数据
const knowledgeTree = ref([]);
const knowledgeLoading = ref(false);
const knowledgeError = ref('');

// 当前编辑的片段id和内容
const editId = ref(null);
const editContent = ref('');
const editDivRef = ref();

// 右侧内容只展示最新一轮第一个选中的目录
const currentFragments = computed(() => {
  if (!selectedDirIds.value.length) return [];
  // 这里用 currentFragmentsMap.value[selectedDirIds.value[0]]，实际开发中请用真实数据
  const fragments = currentFragmentsMap.value[selectedDirIds.value[0]] || [];
  // 限制显示数量，避免性能问题
  return fragments.slice(0, 20);
});

// 键盘事件处理
const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    handleAsk();
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const historyEl = document.querySelector('.gpt-history');
    if (historyEl) {
      historyEl.scrollTop = historyEl.scrollHeight;
    }
  });
};

// 动态调整气泡宽度
/* const adjustBubbleWidth = () => {
  nextTick(() => {
    const bubbles = document.querySelectorAll('.gpt-bubble');
    bubbles.forEach(bubble => {
      const content = bubble.textContent || bubble.innerText;
      const contentLength = content.trim().length;
      
      // 根据内容长度动态调整宽度
      if (contentLength < 20) {
        bubble.style.maxWidth = '200px';
      } else if (contentLength < 50) {
        bubble.style.maxWidth = '300px';
      } else if (contentLength < 100) {
        bubble.style.maxWidth = '400px';
      } else {
        // 长内容使用容器最大宽度
        if (bubble.classList.contains('user')) {
          bubble.style.maxWidth = '400px';
        } else {
          bubble.style.maxWidth = 'calc(100% - 56px)';
        }
      }
    });
  });
};
 */
// 性能监控
const performanceMetrics = ref({
  loadTime: 0,
  renderTime: 0
});

// 记录加载时间
const recordLoadTime = () => {
  const startTime = performance.now();
  return () => {
    performanceMetrics.value.loadTime = performance.now() - startTime;
    console.log(`页面加载耗时: ${performanceMetrics.value.loadTime.toFixed(2)}ms`);
  };
};

// 清理聊天历史（重置为初始状态）
const clearChatHistory = () => {
  chatList.value = [];
  currentFragmentsMap.value = {};
  selectedDirIds.value = [];
  mode.value = 'chat';
  ElMessage.success('已重置会话');
};



// 获取知识库目录树
const loadKnowledgeTree = async () => {
  try {
    knowledgeLoading.value = true;
    knowledgeError.value = '';
    
    // 添加超时处理
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('请求超时')), 30000);
    });
    
    const result = await Promise.race([
      dirTree(),
      timeoutPromise
    ]);
    
    if (result && result.data && result.data.list_path) {
      knowledgeTree.value = result.data.list_path;
      console.log('知识库目录树加载成功:', knowledgeTree.value);
    } else {
      throw new Error('数据格式错误');
    }
  } catch (error) {
    console.error('加载知识库目录树失败:', error);
    if (error.message === '请求超时') {
      knowledgeError.value = '请求超时，请检查网络连接';
    } else if (error.message === '数据格式错误') {
      knowledgeError.value = '数据格式错误，请联系管理员';
    } else {
      knowledgeError.value = '加载知识库失败，请稍后重试';
    }
    ElMessage.error(knowledgeError.value);
  } finally {
    knowledgeLoading.value = false;
  }
};

// 获取指定路径的知识片段
const loadFragments = async (kbPath) => {
  try {
    const result = await fragments({ kb_path: kbPath });
    if (result && result.data) {
      return result.data;
    }
    return [];
  } catch (error) {
    console.error('加载知识片段失败:', error);
    return [];
  }
};

// 将树形结构转换为路径数组
const treeToPaths = (tree, parentPath = []) => {
  let res = [];
  for (const node of tree) {
    const currentPath = [...parentPath, { id: node.path, label: node.title }];
    if (!node.children || node.children.length === 0) {
      res.push({
        id: node.path,
        path: currentPath,
        kbPath: node.path
      });
    } else if (node.children) {
      res = res.concat(treeToPaths(node.children, currentPath));
    }
  }
  return res;
};

async function handleAsk() {
  if (!question.value.trim()) return;
  
  // 1. 追加用户消息
  chatList.value.push({ role: 'user', content: question.value });
  
  // 2. 立即切换到聊天记录页面
  mode.value = 'result';
  
  // 3. 清空输入框
  question.value = '';
  
  // 4. 滚动到底部显示新消息
  scrollToBottom();
  
  // 5. 添加AI消息占位符，显示加载状态
  chatList.value.push({
    role: 'ai',
    content: 'loading', // 使用特殊标识表示加载状态
    dirs: [],
    fragments: []
  });
  
  // 6. 再次滚动到底部
  scrollToBottom();

  try {
    // 7. 调用知识库搜索接口
    const searchParams = {
      question: chatList.value[chatList.value.length - 2].content, // 获取用户问题
      topk: 3,
      filter_nodes: [],
      filter_mode: "delete",
      filter_type: 1,
      show_image: true,
      rerank: "llm",
      ask: true,
      ask_multimodal: true,
      ask_agent: true
    };

    console.log('搜索参数:', searchParams);
    
    // 8. 调用发送接口，传递searchParams参数
    const searchResult = await searchKnowledge(searchParams);
    console.log('发送接口返回结果:', searchResult);
    
    // 4. 使用真实的知识库目录树
  /*   if (knowledgeTree.value.length === 0) {
      await loadKnowledgeTree();
    }
     */
    // 5. 使用searchParams中的参数，这里可以根据需要处理
    console.log('搜索参数:', searchParams);
    
    // 6. 使用searchResult.data.fir_path作为知识库树路径，如果没有则使用默认的
    // let dirs = [];
    // if (searchResult && searchResult.data && searchResult.data.fir_path && searchResult.data.fir_path.length > 0) {
    //   // 使用搜索接口返回的路径
    //   dirs = searchResult.data.fir_path.map((path, index) => ({
    //     id: `search_${index}`,
    //     path: path.split('/').map((node, idx) => ({ 
    //       id: `node_${index}_${idx}`, 
    //       label: node 
    //     })),
    //     kbPath: path
    //   }));
    // } 
    
    // 7. 为每个目录加载真实的知识片段
/*     const fragmentsData = {};
    for (const dir of dirs) {
      const fragmentsList = await loadFragments(dir.kbPath);
      fragmentsData[dir.id] = fragmentsList.map(frag => ({
        id: frag.know_id || frag.id,
        content: frag.content || frag.fragment,
        title: frag.fragment || frag.title,
        path: dir.kbPath
      }));
    }
 */
    // 8. 更新AI消息内容，使用searchResult.data.answer作为回答内容
    const aiContent = searchResult && searchResult.data && searchResult.data.answer 
      ? searchResult.data.answer 
      : `抱歉，我暂时无法回答您的问题"${searchParams.question}"，请稍后重试。`;
    
    // 更新最后一条AI消息
    const lastAiMessageIndex = chatList.value.length - 1;
    if (chatList.value[lastAiMessageIndex] && chatList.value[lastAiMessageIndex].role === 'ai') {
      chatList.value[lastAiMessageIndex].content = aiContent;
      
      // 只有在成功获取到回答时才添加目录结构和相关数据
      if (searchResult && searchResult.data && searchResult.data.answer) {
        // 使用searchResult.data.res_path作为知识库树路径
        if (searchResult.data.res_path && searchResult.data.res_path.length > 0) {
          const dirs = searchResult.data.res_path.map((path, index) => {
            // 解析路径结构：admin-->建筑工程-->1_自主可控 寒武纪迎来放量周期.pdf-->tables-->总股本4.17亿股，总市值2752.31亿元。一年股价最低9.html
            const pathParts = path.split('-->');
            return {
              id: `search_${index}`,
              path: pathParts.map((node, idx) => ({ 
                id: `node_${index}_${idx}`, 
                label: node 
              })),
              kbPath: path
            };
          });
          
          chatList.value[lastAiMessageIndex].dirs = dirs;
          chatList.value[lastAiMessageIndex].fragments = {}; // 空的片段数据
        }
      } else {
        // 如果没有获取到回答，确保不显示目录结构
        chatList.value[lastAiMessageIndex].dirs = [];
        chatList.value[lastAiMessageIndex].fragments = {};
      }
    }
    
    // 9. 设置当前片段和模式
    selectedDirIds.value = [];
    
    // 10. 滚动到底部显示新消息
    scrollToBottom();
    
  } catch (error) {
    console.error('处理问题失败:', error);
    
    // 更新AI消息为具体的错误信息
    const lastAiMessageIndex = chatList.value.length - 1;
    if (chatList.value[lastAiMessageIndex] && chatList.value[lastAiMessageIndex].role === 'ai') {
      const errorMessage = error.message || '未知错误';
      chatList.value[lastAiMessageIndex].content = `抱歉，处理您的问题时出现了错误：${errorMessage}，请重试。`;
    }
    
    ElMessage.error('处理问题失败，请重试');
  }
}

// 组件挂载时加载知识库数据
onMounted(() => {
  const finishLoad = recordLoadTime();
  finishLoad();
  
  // 不加载本地存储的数据，每次都是新会话
});

function toggleDir(id) {
  const idx = selectedDirIds.value.indexOf(id);
  if (idx === -1) {
    selectedDirIds.value.push(id);
  } else {
    selectedDirIds.value.splice(idx, 1);
  }
}

function handlePolish() {
  if (!selectedDirIds.value.length) return;
  selectedDirIds.value.forEach((id) => {
    (currentFragmentsMap.value[id] || []).forEach((frag) => {
      // 这里可以替换为AI润色接口
      frag.content = '【润色后】' + frag.content;
    });
  });
  // 如果当前正在编辑，刷新编辑内容
  if (editId.value) {
    const editing = currentFragments.value.find(f => f.id === editId.value);
    if (editing) editContent.value = editing.content;
  }
}

async function handleOriginalQA() {
  if (!selectedDirIds.value.length) return;
  try {
    const question = await ElMessageBox.prompt('请输入你的问题', '原文问答', {
      confirmButtonText: '提交',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入你的问题'
    });
    // 假设AI接口返回如下
    const answer = await fakeOriginalQA(question.value, selectedDirIds.value);
    ElMessage.success('AI回答：' + answer);
  } catch (e) {
    // 用户取消
  }
}

// 示例：模拟AI接口
function fakeOriginalQA(q, dirIds) {
  // 实际开发请替换为后端接口
  return Promise.resolve('这是基于原文的AI回答，问题：' + q + '，目录ID：' + dirIds.join(','));
}

async function handleKnowledgeQA() {
  if (!selectedDirIds.value.length) return;
  try {
    const question = await ElMessageBox.prompt('请输入你的问题', '对知识库提问', {
      confirmButtonText: '提交',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入你的问题'
    });
    // 假设AI接口返回如下
    const answer = await fakeKnowledgeQA(question.value, selectedDirIds.value);
    ElMessage.success('AI回答：' + answer);
  } catch (e) {
    // 用户取消
  }
}

// 示例：模拟AI接口
function fakeKnowledgeQA(q, dirIds) {
  // 实际开发请替换为后端接口
  return Promise.resolve('这是基于知识库的AI回答，问题：' + q + '，目录ID：' + dirIds.join(','));
}

// 编辑
function startEdit(frag) {
  editId.value = frag.id;
  editContent.value = frag.content;
  nextTick(() => {
    // 聚焦到可编辑div
    editDivRef.value?.focus();
  });
}
function saveEdit(frag) {
  frag.content = editContent.value;
  editId.value = null;
}
function cancelEdit() {
  editId.value = null;
}

// 删除片段
async function handleDelete(frag) {
  try {
    await ElMessageBox.confirm(
      `确定要删除这个知识片段吗？`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'custom-delete-dialog',
        dangerouslyUseHTMLString: true,
        message: `
          <div class="delete-confirm-content">
            <div class="delete-icon">
              <i class="el-icon-warning"></i>
            </div>
            <div class="delete-title">删除确认</div>
            <div class="delete-message">
              您即将删除知识片段：<strong>"${frag.title || '未命名片段'}"</strong>
            </div>
            <div class="delete-warning">
              <i class="el-icon-info"></i>
              删除后无法恢复，请谨慎操作
            </div>
          </div>
        `
      }
    );
    
    // 执行删除逻辑
    // 这里应该调用删除API
    ElMessage.success('删除成功');
    
    // 从当前片段列表中移除
    const currentDirId = selectedDirIds.value[0];
    if (currentDirId && currentFragmentsMap.value[currentDirId]) {
      const index = currentFragmentsMap.value[currentDirId].findIndex(item => item.id === frag.id);
      if (index > -1) {
        currentFragmentsMap.value[currentDirId].splice(index, 1);
      }
    }
  } catch (error) {
    // 用户取消删除
  }
}
function onEditInput(e) {
  editContent.value = e.target.innerHTML;
}

// 粘贴图片处理
async function handlePaste(e) {
  const items = e.clipboardData && e.clipboardData.items;
  if (!items) return;
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.kind === 'file' && item.type.startsWith('image/')) {
      e.preventDefault();
      const file = item.getAsFile();
      const url = await uploadImage(file);
      // 在光标处插入图片
      insertImageAtCursor(url);
      break;
    }
  }
}
function uploadImage(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target.result);
    reader.readAsDataURL(file);
  });
}
function insertImageAtCursor(url) {
  nextTick(() => {
    const sel = window.getSelection();
    if (!sel || !sel.rangeCount) return;
    const img = document.createElement('img');
    img.src = url;
    img.style.maxWidth = '100%';
    img.style.borderRadius = '8px';
    img.style.margin = '12px 0';
    const range = sel.getRangeAt(0);
    range.insertNode(img);
    // 移动光标到图片后
    range.setStartAfter(img);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    // 更新内容
    editContent.value = editDivRef.value.innerHTML;
  });
}
</script>

<style lang="scss" scoped>
// CSS变量定义
:root {
  --ai-bg-primary: #ffffff;
  --ai-bg-card: #fafafa;
  --ai-bg-glass: rgba(255, 255, 255, 0.8);
  --ai-bg-overlay: rgba(255, 255, 255, 0.95);
  --ai-border: #e5e7eb;
  --ai-border-light: #f3f4f6;
  --ai-text-primary: #1f2937;
  --ai-text-secondary: #6b7280;
  --ai-text-tertiary: #9ca3af;
  --ai-primary: #3b82f6;
  --ai-primary-light: #60a5fa;
  --ai-gradient-primary: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  --ai-radius-sm: 6px;
  --ai-radius-md: 8px;
  --ai-radius-lg: 12px;
  --ai-radius-xl: 16px;
  --ai-shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1);
  --ai-shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
  --ai-shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1);
  --ai-shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.1);
  --ai-shadow-2xl: 0 25px 50px rgba(0, 0, 0, 0.1);
  --ai-blur-sm: blur(8px);
  --ai-blur-md: blur(16px);
  
  // 气泡宽度变量
  --bubble-min-width: 120px;
  --bubble-max-width: calc(100% - 56px);
  --bubble-user-short: 200px;
  --bubble-user-medium: 300px;
  --bubble-user-long: 400px;
  --bubble-ai-content: calc(100% - 56px);
}

// 暗色主题支持
@media (prefers-color-scheme: dark) {
  :root {
    --ai-bg-primary: #0f172a;
    --ai-bg-card: #1e293b;
    --ai-bg-glass: rgba(30, 41, 59, 0.8);
    --ai-bg-overlay: rgba(30, 41, 59, 0.95);
    --ai-border: #334155;
    --ai-border-light: #475569;
    --ai-text-primary: #f1f5f9;
    --ai-text-secondary: #cbd5e1;
    --ai-text-tertiary: #94a3b8;
    --ai-primary: #60a5fa;
    --ai-primary-light: #93c5fd;
    --ai-gradient-primary: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%);
    --ai-shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.3);
    --ai-shadow-md: 0 4px 6px rgba(0, 0, 0, 0.3);
    --ai-shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.3);
    --ai-shadow-xl: 0 20px 25px rgba(0, 0, 0, 0.3);
    --ai-shadow-2xl: 0 25px 50px rgba(0, 0, 0, 0.3);
    
    // 暗色主题气泡宽度变量
    --bubble-min-width: 120px;
    --bubble-max-width: calc(100% - 56px);
    --bubble-user-short: 200px;
    --bubble-user-medium: 300px;
    --bubble-user-long: 400px;
    --bubble-ai-content: calc(100% - 56px);
  }
}

// 高对比度主题支持
@media (prefers-contrast: high) {
  :root {
    --ai-border: #000000;
    --ai-border-light: #333333;
    --ai-text-primary: #000000;
    --ai-text-secondary: #333333;
    --ai-text-tertiary: #666666;
    --ai-primary: #0066cc;
    --ai-primary-light: #0099ff;
  }
}

  .gpt-root {
    background: var(--ai-bg-primary);
    height: 100%;
    color: var(--ai-text-primary);
    display: flex;
    flex-direction: column;
    
    // 自定义滚动条样式
    ::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }
    
    ::-webkit-scrollbar-track {
      background: var(--ai-bg-overlay);
      border-radius: 4px;
    }
    
    ::-webkit-scrollbar-thumb {
      background: var(--ai-border);
      border-radius: 4px;
      
      &:hover {
        background: var(--ai-text-tertiary);
      }
    }
    
    ::-webkit-scrollbar-corner {
      background: var(--ai-bg-overlay);
    }
  }

// 初始问答模式
.gpt-chat-init {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  background: linear-gradient(135deg, var(--ai-bg-primary) 0%, var(--ai-bg-overlay) 100%);
}

.gpt-chat-center {
  text-align: center;
  max-width: 600px;
  width: 100%;
  animation: fadeInUp 0.8s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.gpt-logo {
  width: 80px;
  height: 80px;
  margin: 0 auto 24px;
  background: var(--ai-gradient-primary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  color: white;
  box-shadow: var(--ai-shadow-xl);
  animation: pulse 2s infinite;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    top: -2px;
    left: -2px;
    right: -2px;
    bottom: -2px;
    background: var(--ai-gradient-primary);
    border-radius: 50%;
    z-index: -1;
    opacity: 0.3;
    animation: pulse 2s infinite 0.5s;
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    box-shadow: var(--ai-shadow-xl);
  }
  50% {
    transform: scale(1.05);
    box-shadow: var(--ai-shadow-2xl);
  }
}

.gpt-title {
  font-size: 32px;
  font-weight: 800;
  margin-bottom: 16px;
  background: var(--ai-gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  letter-spacing: -0.5px;
}

.gpt-desc {
  color: var(--ai-text-secondary);
  font-size: 18px;
  line-height: 1.6;
  margin-bottom: 32px;
  opacity: 0.8;
}

.gpt-input-row {
  display: flex;
  gap: 16px;
  align-items: flex-end;
  margin: 0 auto;
  
  .gpt-input {
    flex: 1;
    
    :deep(.el-textarea__inner) {
      background: var(--ai-bg-glass);
      border: 2px solid var(--ai-border);
      border-radius: var(--ai-radius-xl);
      color: var(--ai-text-primary);
      font-size: 16px;
      padding: 16px 20px;
      resize: none;
      transition: all 0.3s ease;
      outline: none;
      
      &:hover {
        border-color: var(--ai-primary-light);
        box-shadow: var(--ai-shadow-sm);
      }
      
      &:focus {
        border-color: var(--ai-primary);
        box-shadow: var(--ai-shadow-md);
        transform: translateY(-2px);
        background: var(--ai-bg-overlay);
      }
      
      &:focus-visible {
        outline: 2px solid var(--ai-primary);
        outline-offset: 2px;
      }
      
      &::placeholder {
        color: var(--ai-text-tertiary);
        transition: color 0.3s ease;
      }
      
      &:focus::placeholder {
        color: var(--ai-text-secondary);
      }
    }
  }
  
  .gpt-send-btn {
    background: var(--ai-gradient-primary);
    border: none;
    color: white;
    width: 56px;
    height: 56px;
    border-radius: var(--ai-radius-xl);
    box-shadow: var(--ai-shadow-lg);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    font-size: 20px;
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
      transition: left 0.5s;
    }
    
    &:hover {
      transform: translateY(-2px) scale(1.05);
      box-shadow: var(--ai-shadow-xl);
      
      &::before {
        left: 100%;
      }
    }
    
    &:active {
      transform: translateY(0) scale(0.98);
    }
    
    &:focus {
      outline: 2px solid var(--ai-primary);
      outline-offset: 2px;
    }
  }
}

// 主界面
.gpt-main {
  flex: 1;
  display: flex;
  height: calc(100vh - 60px);
  min-height: 0; // 确保flex子元素可以正确计算高度
  overflow: hidden; // 防止内容溢出
}

// 左侧聊天区域
.gpt-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--ai-border);
  background: var(--ai-bg-card);
  backdrop-filter: var(--ai-blur-md);
  position: relative;
  overflow: hidden;
  min-height: 0; // 确保flex子元素可以正确计算高度
  height: 100%; // 确保高度正确计算
}

.gpt-history {
  flex: 1;
  padding: 24px;
  padding-bottom: 200px; // 为底部固定输入框留出空间
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-height: 0; // 确保flex子元素可以正确计算高度
  height: 100%; // 确保高度正确计算
  
  // 自定义滚动条样式
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: var(--ai-bg-overlay);
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: var(--ai-border);
    border-radius: 3px;
    
    &:hover {
      background: var(--ai-text-tertiary);
    }
  }
}

// 欢迎页面
.gpt-welcome {
  text-align: center;
  padding: 60px 20px;
  animation: fadeInUp 0.8s ease-out;
  
  .welcome-icon {
    font-size: 64px;
    margin-bottom: 24px;
    opacity: 0.8;
  }
  
  .welcome-title {
    font-size: 24px;
    font-weight: 600;
    color: var(--ai-text-primary);
    margin-bottom: 12px;
  }
  
  .welcome-desc {
    font-size: 16px;
    color: var(--ai-text-secondary);
    line-height: 1.6;
    max-width: 400px;
    margin: 0 auto;
    opacity: 0.8;
  }
}

// 消息容器
.gpt-message {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  
  &:last-child {
    margin-bottom: 0;
  }
  
    &.user {
    flex-direction: row-reverse; // 用户消息头像在右边
    animation: slideInRight 0.5s ease-out;
    
    .gpt-bubble {
      margin-left: 0;
      margin-right: 0; // 移除右边距，让气泡紧贴头像
    }
  }
  
  &.ai {
    flex-direction: row; // AI消息头像在左边
    justify-content: flex-start;
    animation: slideInLeft 0.5s ease-out;
    
    .gpt-bubble {
      margin-right: 0;
      margin-left: 0; // 移除左边距，让气泡紧贴头像
    }
  }
  
  .message-avatar {
    flex-shrink: 0;
    
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
      color: white;
      box-shadow: var(--ai-shadow-sm);
      transition: all 0.3s ease;
      
      &.user {
        background: var(--ai-gradient-primary);
        
        &:hover {
          transform: scale(1.05);
          box-shadow: var(--ai-shadow-md);
        }
      }
      
      &.ai {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        
        &:hover {
          transform: scale(1.05);
          box-shadow: var(--ai-shadow-md);
        }
      }
    }
  }
}

.gpt-bubble {
  flex: 0 1 auto; // 不强制拉伸，根据内容调整宽度
  min-width: 120px; // 最小宽度
  padding: 16px 20px;
  border-radius: var(--ai-radius-xl);
  line-height: 1.6;
  font-size: 15px;
  position: relative;
  cursor: default;
  word-wrap: break-word;
  overflow-wrap: break-word;
  white-space: pre-wrap; // 保持换行和空格
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: var(--ai-shadow-md);
  }
  
  &.user {
    background: var(--ai-gradient-primary);
    color: white;
    border-bottom-right-radius: var(--ai-radius-sm);
    box-shadow: var(--ai-shadow-md);
    
    // 用户消息通常较短，限制最大宽度
    // max-width: 300px;
  }
  
  &.ai {
    background: var(--ai-bg-glass);
    border: 1px solid var(--ai-border);
    color: var(--ai-text-primary);
    border-bottom-left-radius: var(--ai-radius-sm);
    box-shadow: var(--ai-shadow-sm);
    
    // AI消息可能较长，允许更宽
    max-width: calc(100% - 56px);
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    box-shadow: var(--ai-shadow-xl);
  }
  50% {
    transform: scale(1.05);
    box-shadow: var(--ai-shadow-2xl);
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes shimmer {
  0% {
    background-position: -200px 0;
  }
  100% {
    background-position: calc(200px + 100%) 0;
  }
}

@keyframes bounce {
  0%, 20%, 53%, 80%, 100% {
    transform: translate3d(0, 0, 0);
  }
  40%, 43% {
    transform: translate3d(0, -8px, 0);
  }
  70% {
    transform: translate3d(0, -4px, 0);
  }
  90% {
    transform: translate3d(0, -2px, 0);
  }
}

// 目录结构 - 新样式
.gpt-dir-list-compact {
  margin-left: 56px; // 与AI头像对齐
  padding: 20px;
  background: var(--ai-bg-glass);
  border-radius: var(--ai-radius-xl);
  border: 1px solid var(--ai-border-light);
  max-width: calc(100% - 56px); // 与气泡宽度一致
  animation: slideInLeft 0.3s ease-out;
  box-shadow: var(--ai-shadow-sm);
  
  .gpt-dir-header {
    margin-bottom: 16px;
    text-align: center;
    
    .gpt-dir-title {
      display: block;
      font-size: 16px;
      font-weight: 600;
      color: var(--ai-text-primary);
      margin-bottom: 4px;
    }
    
    .gpt-dir-subtitle {
      display: block;
      font-size: 12px;
      color: var(--ai-text-tertiary);
    }
  }
  
  .gpt-dir-items {
    margin-bottom: 20px;
  }
  
  .gpt-dir-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    border-radius: var(--ai-radius-lg);
    cursor: pointer;
    transition: all 0.3s ease;
    margin-bottom: 8px;
    border: 1px solid transparent;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &:hover {
      background: var(--ai-bg-overlay);
      border-color: var(--ai-primary-light);
      transform: translateX(4px);
    }
    
    &.selected {
      background: var(--ai-bg-overlay);
      border-color: var(--ai-primary);
      box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
      
      .gpt-dir-checkbox {
        :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
          background: var(--ai-primary);
          border-color: var(--ai-primary);
        }
      }
    }
    
    .gpt-dir-checkbox {
      flex-shrink: 0;
      
      :deep(.el-checkbox) {
        .el-checkbox__input {
          .el-checkbox__inner {
            width: 18px;
            height: 18px;
            border: 2px solid var(--ai-border);
            border-radius: 4px;
            background: var(--ai-bg-glass);
            transition: all 0.3s ease;
            
            &:hover {
              border-color: var(--ai-primary-light);
            }
          }
          
          &.is-checked .el-checkbox__inner {
            background: var(--ai-primary);
            border-color: var(--ai-primary);
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
          }
        }
      }
    }
    
    .gpt-dir-content {
      flex: 1;
      min-width: 0;
      
      .gpt-dir-path {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 14px;
        color: var(--ai-text-secondary);
        flex-wrap: wrap;
        
        .gpt-dir-path-label {
          color: var(--ai-text-primary);
          font-weight: 500;
          background: var(--ai-bg-overlay);
          padding: 2px 6px;
          border-radius: var(--ai-radius-sm);
          border: 1px solid var(--ai-border-light);
        }
        
        .gpt-dir-path-sep {
          color: var(--ai-text-tertiary);
          font-weight: 300;
          margin: 0 2px;
        }
      }
    }
  }
  
  .gpt-dir-actions {
    display: flex;
    gap: 12px;
    justify-content: center;
    padding-top: 16px;
    border-top: 1px solid var(--ai-border-light);
    
    .action-btn {
      padding: 8px 16px;
      font-size: 13px;
      font-weight: 500;
      border-radius: var(--ai-radius-lg);
      transition: all 0.3s ease;
      box-shadow: var(--ai-shadow-sm);
      min-width: 100px;
      
      &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: var(--ai-shadow-md);
      }
      
      &:active:not(:disabled) {
        transform: translateY(0);
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
      }
      
      .el-icon {
        margin-right: 6px;
        font-size: 14px;
      }
    }
  }
}

.gpt-dir-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: var(--ai-radius-md);
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 8px;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 3px;
    height: 100%;
    background: var(--ai-primary);
    transform: scaleY(0);
    transition: transform 0.3s ease;
  }
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &:hover {
    background: var(--ai-bg-glass);
    transform: translateX(4px);
    
    &::before {
      transform: scaleY(1);
    }
  }
  
  &.selected {
    background: var(--ai-bg-overlay);
    border: 1px solid var(--ai-primary);
    
    &::before {
      transform: scaleY(1);
    }
    
    .el-checkbox {
      :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
        background: var(--ai-primary);
        border-color: var(--ai-primary);
      }
    }
  }
  
  &.history-dir-row {
    opacity: 0.6;
    cursor: default;
    
    &:hover {
      transform: none;
      background: transparent;
      
      &::before {
        transform: scaleY(0);
      }
    }
  }
}

.gpt-dir-path {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: var(--ai-text-secondary);
  
  .gpt-dir-path-label {
    color: var(--ai-text-primary);
    font-weight: 500;
  }
  
  .gpt-dir-path-sep {
    color: var(--ai-text-tertiary);
    font-weight: 300;
  }
}

.gpt-dir-actions-bottom {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--ai-border-light);
  
  .el-button {
    background: var(--ai-bg-glass);
    border: 1px solid var(--ai-border);
    color: var(--ai-text-secondary);
    border-radius: var(--ai-radius-lg);
    padding: 10px 18px;
    font-size: 13px;
    font-weight: 500;
    transition: all 0.3s ease;
    box-shadow: var(--ai-shadow-sm);
    
    &:hover:not(:disabled) {
      border-color: var(--ai-primary);
      color: var(--ai-primary);
      background: var(--ai-bg-overlay);
      transform: translateY(-2px);
      box-shadow: var(--ai-shadow-md);
    }
    
    &:active:not(:disabled) {
      transform: translateY(0);
    }
    
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
    }
  }
}

// 左侧底部固定提问框
.gpt-input-area-fixed {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px 24px;
  border-top: 1px solid var(--ai-border-light);
  background: #ffffff;
  backdrop-filter: var(--ai-blur-sm);
  z-index: 10;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
  height: auto; // 确保高度自动计算
  
  .gpt-input-status {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .status-indicator {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 12px;
      color: var(--ai-text-tertiary);
      
      .status-dot {
        width: 8px;
        height: 8px;
        background: #10b981;
        border-radius: 50%;
        animation: pulse 2s infinite;
      }
    }
    
    .status-actions {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .reset-btn {
        padding: 4px 12px;
        font-size: 12px;
        border-radius: var(--ai-radius-sm);
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: var(--ai-shadow-sm);
        }
        
        .el-icon {
          margin-right: 4px;
          font-size: 14px;
        }
      }
      
      .help-text {
        .el-icon {
          color: var(--ai-text-tertiary);
          font-size: 14px;
          cursor: help;
          transition: color 0.3s ease;
          
          &:hover {
            color: var(--ai-primary);
          }
        }
      }
    }
  }
  
  .gpt-input-row {
    margin: 0;
    max-width: none;
    
    .gpt-input {
      :deep(.el-textarea__inner) {
        background: var(--ai-bg-glass);
        border: 1px solid var(--ai-border);
        border-radius: var(--ai-radius-lg);
        padding: 12px 16px;
        font-size: 14px;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: var(--ai-primary-light);
          box-shadow: var(--ai-shadow-sm);
        }
        
        &:focus {
          border-color: var(--ai-primary);
          box-shadow: var(--ai-shadow-md);
          transform: translateY(-1px);
        }
      }
    }
    
    .gpt-send-btn {
      width: 48px;
      height: 48px;
      font-size: 18px;
      border-radius: var(--ai-radius-lg);
      background: var(--ai-gradient-primary);
      border: none;
      color: white;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: var(--ai-shadow-md);
      }
      
      &:active {
        transform: translateY(0);
      }
    }
  }
}

// 右侧内容区域
.gpt-right {
  width: 400px;
  background: var(--ai-bg-card);
  backdrop-filter: var(--ai-blur-md);
  border-left: 1px solid var(--ai-border);
  display: flex;
  flex-direction: column;
  box-shadow: -4px 0 20px rgba(0, 0, 0, 0.05);
}

.gpt-content-scroll {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.gpt-tip {
  text-align: center;
  color: var(--ai-text-secondary);
  padding: 80px 20px;
  animation: fadeInUp 0.6s ease-out;
  
  .tip-icon {
    font-size: 64px;
    margin-bottom: 24px;
    opacity: 0.6;
    animation: bounce 2s infinite;
  }
  
  .tip-title {
    font-size: 20px;
    font-weight: 600;
    color: var(--ai-text-primary);
    margin-bottom: 12px;
  }
  
  .tip-desc {
    font-size: 14px;
    line-height: 1.6;
    max-width: 300px;
    margin: 0 auto;
    opacity: 0.8;
  }
}

.gpt-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: var(--ai-text-secondary);
  
  .el-loading-spinner {
    .circular {
      width: 32px;
      height: 32px;
    }
  }
}

.gpt-skeleton {
  padding: 20px;
  
  .skeleton-item {
    height: 20px;
    background: linear-gradient(90deg, var(--ai-bg-glass) 25%, var(--ai-bg-overlay) 50%, var(--ai-bg-glass) 75%);
    background-size: 200px 100%;
    animation: shimmer 1.5s infinite;
    border-radius: var(--ai-radius-sm);
    margin-bottom: 16px;
    
    &:nth-child(1) { width: 80%; }
    &:nth-child(2) { width: 60%; }
    &:nth-child(3) { width: 90%; }
    &:nth-child(4) { width: 70%; }
    &:nth-child(5) { width: 50%; }
  }
}

.gpt-error {
  text-align: center;
  padding: 60px 20px;
  animation: fadeInUp 0.6s ease-out;
  
  .error-icon {
    font-size: 48px;
    margin-bottom: 20px;
    opacity: 0.7;
  }
  
  .error-title {
    font-size: 18px;
    font-weight: 600;
    color: #ef4444;
    margin-bottom: 12px;
  }
  
  .error-desc {
    font-size: 14px;
    color: var(--ai-text-secondary);
    margin-bottom: 20px;
    line-height: 1.6;
  }
  
  .retry-btn {
    background: var(--ai-gradient-primary);
    border: none;
    color: white;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: var(--ai-shadow-md);
    }
  }
}

.gpt-fragment-card {
  background: var(--ai-bg-glass);
  border: 1px solid var(--ai-border);
  border-radius: var(--ai-radius-lg);
  padding: 24px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  position: relative;
  animation: slideInRight 0.5s ease-out;
  
  &:hover {
    border-color: var(--ai-primary-light);
    box-shadow: var(--ai-shadow-lg);
    transform: translateY(-3px);
  }
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .gpt-fragment-toolbar {
    position: absolute;
    top: 16px;
    right: 16px;
    display: flex;
    gap: 8px;
    opacity: 0;
    transition: opacity 0.3s ease;
    
    .el-button {
      padding: 6px 12px;
      font-size: 12px;
      border-radius: var(--ai-radius-md);
      box-shadow: var(--ai-shadow-sm);
      
      .el-icon {
        margin-right: 4px;
        font-size: 14px;
      }
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: var(--ai-shadow-md);
      }
    }
  }
  
  &:hover .gpt-fragment-toolbar:not(.edit-mode) {
    opacity: 1;
  }
  
  .gpt-fragment-toolbar.edit-mode {
    opacity: 1;
    background: var(--ai-bg-overlay);
    padding: 8px 12px;
    border-radius: var(--ai-radius-md);
    backdrop-filter: var(--ai-blur-sm);
    border: 1px solid var(--ai-border-light);
  }
  
  .gpt-fragment-rich {
    margin-bottom: 16px;
    line-height: 1.6;
    color: var(--ai-text-primary);
    
    :deep(p) {
      margin-bottom: 12px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    :deep(h1, h2, h3, h4, h5, h6) {
      color: var(--ai-text-primary);
      margin: 16px 0 8px;
      font-weight: 600;
    }
    
    :deep(ul, ol) {
      padding-left: 20px;
      margin: 12px 0;
    }
    
    :deep(li) {
      margin-bottom: 6px;
    }
    
    :deep(code) {
      background: var(--ai-bg-overlay);
      padding: 2px 6px;
      border-radius: 4px;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 13px;
      color: var(--ai-primary);
    }
    
    :deep(blockquote) {
      border-left: 4px solid var(--ai-primary);
      padding-left: 16px;
      margin: 16px 0;
      color: var(--ai-text-secondary);
      font-style: italic;
    }
  }
  
  .gpt-fragment-meta {
    display: flex;
    align-items: center;
    gap: 16px;
    padding-top: 16px;
    border-top: 1px solid var(--ai-border-light);
    
    .meta-item {
      display: flex;
      align-items: center;
      gap: 6px;
      color: var(--ai-text-tertiary);
      font-size: 12px;
      
      .el-icon {
        font-size: 14px;
      }
    }
  }
  
  .gpt-fragment-editable {
    min-height: 120px;
    outline: 1px solid var(--ai-border);
    padding: 16px;
    border-radius: var(--ai-radius-md);
    background: var(--ai-bg-glass);
    color: var(--ai-text-primary);
    line-height: 1.6;
    transition: all 0.3s ease;
    
    &:focus {
      outline: 2px solid var(--ai-primary);
      box-shadow: var(--ai-shadow-sm);
      background: var(--ai-bg-overlay);
    }
    
    &::placeholder {
      color: var(--ai-text-tertiary);
    }
  }
}

// 美化的删除确认弹窗样式
:deep(.custom-delete-dialog) {
  .el-message-box__header {
    padding: 24px 24px 0;
    
    .el-message-box__title {
      font-size: 18px;
      font-weight: 600;
      color: #1f2937;
    }
  }
  
  .el-message-box__content {
    padding: 20px 24px;
    
    .delete-confirm-content {
      text-align: center;
      
      .delete-icon {
        margin-bottom: 16px;
        
        i {
          font-size: 48px;
          color: #f59e0b;
        }
      }
      
      .delete-title {
        font-size: 20px;
        font-weight: 600;
        color: #1f2937;
        margin-bottom: 12px;
      }
      
      .delete-message {
        font-size: 14px;
        color: #6b7280;
        margin-bottom: 16px;
        line-height: 1.5;
        
        strong {
          color: #3b82f6;
          font-weight: 600;
        }
      }
      
      .delete-warning {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 12px 16px;
        background: rgba(239, 68, 68, 0.1);
        border: 1px solid rgba(239, 68, 68, 0.2);
        border-radius: 8px;
        color: #dc2626;
        font-size: 13px;
        
        i {
          font-size: 16px;
        }
      }
    }
  }
  
  .el-message-box__btns {
    padding: 0 24px 24px;
    
    .el-button {
      padding: 10px 24px;
      font-size: 14px;
      font-weight: 500;
      border-radius: 8px;
      transition: all 0.3s ease;
      
      &.el-button--default {
        border-color: #d1d5db;
        color: #6b7280;
        
        &:hover {
          border-color: #9ca3af;
          color: #374151;
          background: #f9fafb;
        }
      }
      
      &.el-button--primary {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        border-color: #ef4444;
        color: white;
        
        &:hover {
          background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
          border-color: #dc2626;
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
        }
      }
    }
  }
}

// 加载动画样式
.loading-animation {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  
  .loading-dots {
    display: flex;
    gap: 8px;
    margin-bottom: 12px;
    
    span {
      width: 8px;
      height: 8px;
      background: var(--ai-primary);
      border-radius: 50%;
      animation: loadingBounce 1.4s ease-in-out infinite both;
      
      &:nth-child(1) {
        animation-delay: -0.32s;
      }
      
      &:nth-child(2) {
        animation-delay: -0.16s;
      }
      
      &:nth-child(3) {
        animation-delay: 0s;
      }
    }
  }
  
  .loading-text {
    color: var(--ai-text-secondary);
    font-size: 14px;
    font-weight: 500;
  }
}

@keyframes loadingBounce {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

// 打印样式支持
@media print {
  .gpt-input-area-fixed,
  .gpt-fragment-toolbar,
  .gpt-dir-actions-bottom {
    display: none !important;
  }
  
  .gpt-root {
    background: white !important;
    color: black !important;
  }
  
  .gpt-bubble {
    break-inside: avoid;
    page-break-inside: avoid;
  }
  
  .gpt-fragment-card {
    break-inside: avoid;
    page-break-inside: avoid;
    border: 1px solid #ccc !important;
    box-shadow: none !important;
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .gpt-main {
    flex-direction: column;
    height: auto;
  }
  
  .gpt-right {
    width: 100%;
    border-left: none;
    border-top: 1px solid var(--ai-border);
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.05);
  }
  
  .gpt-dir-actions-bottom {
    flex-wrap: wrap;
    
    .el-button {
      flex: 1;
      min-width: 120px;
    }
  }
  
  .gpt-input-area-fixed {
    position: relative;
    box-shadow: none;
  }
  
  .gpt-history {
    padding-bottom: 24px;
  }
}

@media (max-width: 768px) {
  .gpt-chat-init {
    padding: 20px;
  }
  
  .gpt-title {
    font-size: 24px;
  }
  
  .gpt-desc {
    font-size: 16px;
  }
  
  .gpt-input-row {
    flex-direction: column;
    align-items: stretch;
    
    .gpt-send-btn {
      width: 100%;
      height: 48px;
      border-radius: var(--ai-radius-lg);
    }
  }
  
  .gpt-history {
    padding: 16px;
    padding-bottom: 80px;
    
    // 移动端滚动条优化
    &::-webkit-scrollbar {
      width: 4px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: var(--ai-border-light);
      border-radius: 2px;
    }
  }
  
  .gpt-welcome {
    padding: 40px 16px;
    
    .welcome-icon {
      font-size: 48px;
    }
    
    .welcome-title {
      font-size: 20px;
    }
    
    .welcome-desc {
      font-size: 14px;
    }
  }
  
  .gpt-bubble {
    max-width: calc(100% - 48px); // 移动端头像较小
    min-width: 80px; // 移动端最小宽度较小
    font-size: 14px;
    padding: 12px 16px;
    
    &.user {
      max-width: 250px;
    }
    
    &.ai {
      max-width: calc(100% - 48px); // 移动端AI消息最大宽度
    }
  }
  
  .gpt-dir-list-compact {
    margin-left: 48px; // 移动端头像较小
    max-width: calc(100% - 48px);
    padding: 16px;
    
    .gpt-dir-header {
      margin-bottom: 12px;
      
      .gpt-dir-title {
        font-size: 14px;
      }
      
      .gpt-dir-subtitle {
        font-size: 11px;
      }
    }
    
    .gpt-dir-item {
      padding: 10px 12px;
      
      .gpt-dir-content {
        .gpt-dir-path {
          font-size: 13px;
          
          .gpt-dir-path-label {
            padding: 1px 4px;
            font-size: 12px;
          }
        }
      }
    }
    
    .gpt-dir-actions {
      flex-direction: column;
      gap: 8px;
      
      .action-btn {
        width: 100%;
        min-width: auto;
        justify-content: center;
      }
    }
  }
  
  .gpt-input-area-fixed {
    padding: 16px;
    
    .gpt-input-status {
      margin-bottom: 8px;
    }
  }
  
  .gpt-fragment-card {
    padding: 16px;
    
    .gpt-fragment-toolbar {
      position: static;
      opacity: 1;
      margin-bottom: 12px;
      justify-content: flex-end;
    }
  }
}

@media (max-width: 480px) {
  .gpt-logo {
    width: 60px;
    height: 60px;
    font-size: 28px;
  }
  
  .gpt-title {
    font-size: 20px;
  }
  
  .gpt-desc {
    font-size: 14px;
  }
  
  .gpt-bubble {
    max-width: calc(100% - 40px); // 小屏幕头像较小
    min-width: 60px; // 小屏幕最小宽度更小
    font-size: 13px;
    padding: 10px 14px;
    
    &.user {
      max-width: 200px; // 小屏幕用户消息最大宽度更小
    }
    
    &.ai {
      max-width: calc(100% - 40px); // 小屏幕AI消息最大宽度
    }
  }
  
  .gpt-dir-list-vertical {
    margin-left: 40px; // 移动端头像较小
    max-width: calc(100% - 40px);
  }
  
  .gpt-input-area-fixed {
    padding: 12px 16px;
    
    .status-actions {
      flex-direction: column;
      gap: 8px;
      
      .reset-btn {
        width: 100%;
        justify-content: center;
      }
    }
  }
  
  .gpt-fragment-card {
    padding: 12px;
    
    .gpt-fragment-toolbar {
      position: static;
      opacity: 1;
      margin-bottom: 8px;
      justify-content: center;
    }
  }
  
  .gpt-message {
    gap: 12px; // 移动端间距较小
    
    .message-avatar {
      .avatar {
        width: 32px;
        height: 32px;
        font-size: 14px;
      }
    }
  }
}
</style>
